package com.gitee.ricesugar.service.impl;

import com.gitee.ricesugar.controller.request.BaseRequest;
import com.gitee.ricesugar.entity.Book;
import com.gitee.ricesugar.entity.BookRecord;
import com.gitee.ricesugar.mapper.BookMapper;
import com.gitee.ricesugar.service.IBookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class BookService implements IBookService {

    @Autowired
    BookMapper bookMapper;

    @Override
    public void add(Book obj) {
        bookMapper.add(obj);
    }

    @Override
    public PageInfo<Book> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<Book> obj = bookMapper.listByCondition(baseRequest);
        return new PageInfo<>(obj);
    }

    @Override
    public PageInfo<BookRecord> record(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<BookRecord> obj = bookMapper.listRecordByCondition(baseRequest);
        return new PageInfo<>(obj);
    }

    @Override
    public Object getByISBN(String isbn) {
        return bookMapper.getByISBN(isbn);
    }

    @Override
    public void update(Book obj) {
        Date date = new Date();
        obj.setAddDate(date);
        bookMapper.updateByISBN(obj);
    }

    @Override
    public void deleteByISBN(String isbn) {
        bookMapper.deleteByISBN(isbn);
    }

    @Override
    public void deleteRecordById(Integer id) {
        bookMapper.deleteRecordById(id);
    }

    @Override
    public void borrow(String username, List<Book> list) {
        for (Book book : list) {
            HashMap<Object, Object> obj = new HashMap<>();
            obj.put("username", username);
            obj.put("isbn", book.getIsbn());
            bookMapper.borrow(obj);
        }
    }

    @Override
    public void returnBook(Integer id) {
        bookMapper.returnBook(id);
    }
}
